var api = require('../../utils/api.js')
Page({

  data: {
    list: [],
    focus_index: 0,
    code_value: [],
    num_length: 4,
    height: '',
    open_tell: '',
    isFocus: true,
    touch: true
  },
  // 手指点击触碰后离开锁定事件
  getFocus: function () {
    this.setData({
      isFocus: true
    })
  },

  onLoad: function () {
    this.setData({
      open_tell: wx.getStorageSync('open_tell')
    })
  },

  onShow: function() {
    wx.onKeyboardHeightChange(res => {
      console.log(res.height)
      if (res.height > 0) {
        this.setData({
          height: res.height + 15
        })
      }
    })
  },

  onBlur: function(e) {
    this.setData({
      height: 15
    })
  },

  inputNum: function (e) {
    var value = e.detail.value;
    this.setData({
      code_value: value.split(""),
      list: [] // 每次输入的时候清空搜索的内容
    })
    if (value.length == 4) {
      wx.hideKeyboard()
      this.search();
    }
  },
  search: function () {
    wx.showLoading({
      title: '加载中...'
    })
    var that = this;
    let data = {
      code: that.data.code_value.join(""),
      userid_locked: wx.getStorageSync("userid_locked")
    }
    api.form_('Scan/get_community', data, null, function success(res) {
      that.setData({
        list: res.data.data
      })
      wx.hideLoading();
    }, function fail(e) {
      console.log(e)
      wx.hideLoading();
    })
  },

  // 6折换电活动
  six_discount: function (url, params = null, paramter = null) {
    wx.setStorageSync('discount', url)
    let data = {
      qrcode: url,
      userid_locked: wx.getStorageSync("userid_locked") ? wx.getStorageSync("userid_locked") : 0
    }
    api.form_('Activity/enter_activity_h', data, null, function success(res) {
      console.log(res)
      if (res.data.result_code == '500') {
        if (params && paramter) {
          let data = {
            userid_locked: wx.getStorageSync('userid_locked'),
            t_id: paramter
          }
          api.active('Trans/records', data, function sucess(res) {
            console.log(res)
            if (res.data.code == 1) {
              // 扫码商城
              wx.redirectTo({
                url: '/pages/product/product?id=' + params + '&user_id=' + paramter
              })
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })
            }
          })
        } else if (params) {
          // 换电
          if (params.match('type')) {
            let param = params.split('type')[0]
            wx.navigateTo({
              url: '../battery/battery?url=' + res.data.data.url + '&hd=' + param + '&type=1'
            })
          } else {
            wx.navigateTo({
              url: '../battery/battery?url=' + res.data.data.url + '&hd=' + params
            })
          }
        } else {
          // 6折换电
          wx.navigateTo({
            url: '../battery/battery?url=' + res.data.data.url
          })
        }
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  // 邀请购车
  buy_car: function (params) {
    this.setData({
      user_id: params
    })
    let data = {
      userid_locked: wx.getStorageSync('userid_locked'),
      referrer_id: params
    }
    api.form_('buycar/recommend', data, null, function success(res) {
      console.log(res.data)
      if (res.data.result_code == '373') {
        wx.showToast({
          title: res.data.msg,
          icon: 'loading',
          success: function () {
            wx.redirectTo({
              url: '/pages/buyCar/procedure/procedure'
            })
          }
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  // 扫描设备码
  scan_charge: function () {
    let data = {
      userid_locked: wx.getStorageSync('userid_locked'),
      str: wx.getStorageSync('str')
    }
    api.form_('Scan/scan', data, null, function success(res) {
      console.log(res.data)
      switch (res.data.result_code) {
        case "300": //成功
          let uri = JSON.stringify(res.data.data)
          let data = encodeURIComponent(uri)
          wx.setStorageSync('operator_phone', res.data.data.operator_phone)
          wx.redirectTo({
            url: '../openCharging/openCharging?support_month_card=' + res.data.support_month_card + '&num_id=' + res.data.num_id + '&data=' + data + '&location=111'
          })
          break;
        default: //其他
          wx.showModal({
            title: '温馨提示',
            content: res.data.msg
          })
          break;
      }
    }, function fail(e) {
      console.log(e)
    })
  },

  // 邀请新用户
  new_friend: function (params) {
    this.setData({
      userid: params
    })
    if (!wx.getStorageSync('userid_locked')) {
      wx.redirectTo({
        url: '../authorize/authorize?userid=' + params
      })
    } else {
      wx.showToast({
        title: '您不是新用户',
        icon: 'none'
      })
    }
  },

  // 小程序内部扫码
  sweepCode: function (e) {
    let that = this
    if (that.data.touch) {
      that.setData({
        touch: false
      })
      wx.scanCode({
        success: (res) => {
          console.log(res.result)
          let url = res.result // 外部扫码
          let userid = that.GetQueryString(url, "userid") //邀请新用户 https://cd1a.cn/pages/index/index?userid=
          let user_id = that.GetQueryString(url, "user_id") //购车邀请好友 https://cd1a.cn/pages/index/index?user_id=
          let six_discount = that.GetQueryString(url, 'six') //6折换电活动的二维码 && 推荐代理
          let s = that.GetQueryString(url, 's') // 设备
          // 6折换电活动 && 推荐代理 && 扫码商城
          if (six_discount) {
            let a_id = that.GetQueryString(url, 'a_id')
            let goods_id = that.GetQueryString(url, 'goods_id')
            let users_id = that.GetQueryString(url, 'users_id')
            let hd = that.GetQueryString(url, 'hd')
            if (a_id) {
              that.six_discount(url, a_id) // 推荐代理
            } else if (goods_id && users_id) {
              that.six_discount(url, goods_id, users_id) // 扫码商城
            } else if (hd) {
              that.six_discount(url, hd) // 换电 (邀请好友助力)
            } else {
              that.six_discount(url) // 6折换电 换电
            }
          }
          // 邀请新用户
          if (userid) {
            that.new_friend(userid)
          }
  
          // 购车邀请好友
          if (user_id) {
            that.buy_car(user_id)
          }
  
          // 设备
          if (s) {
            if (url.indexOf('?') == '-1') {
              wx.setStorageSync('str', url)
              that.scan_charge()
            } else {
              if (url.split('?')[1].split('=')[0] == 's') {
                wx.setStorageSync('str', url)
                that.scan_charge()
              } else {
                that.six_discount(url)
              }
            }
          }
  
          // 其他的外部扫码没有这些判断的都走设备扫码
          if (!user_id && !userid && !six_discount && !s) {
            if (url.indexOf('?') == '-1') {
              wx.setStorageSync('str', url)
              that.scan_charge()
            } else {
              // fn 粉丝团
              that.six_discount(url)
            }
          }
        },
      })
      setTimeout(() => {
        that.setData({
          touch: true
        })
      }, 3000)
    }
  },

  // 正则验证
  GetQueryString: function (url, name) {
    let reg = new RegExp("(^|/?|&)" + name + "=([^&]*)(&|$)", "i");
    let r = url.substr(1).match(reg);
    if (r != null) {
      return unescape(r[2]);
    };
    return null;
  },

  //确定开启
  remoteOpen: function (e) {
    let that = this;
    that.setData({
      check_index: e.target.dataset.index
    })

    wx.showModal({
      title: "开启端口",
      content: "是否确认开启该社区端口",
      showCancel: true,
      cancelText: "取消",
      cancelColor: "#000",
      confirmText: "开启",
      confirmColor: "#0da297",
      success: function (res) {
        if (res.confirm) {
          if (!that.data.list[that.data.check_index]) return;
          var scan = that.data.list[that.data.check_index].scan;
          wx.setStorageSync("str", scan)
          let data = {
            userid_locked: wx.getStorageSync('userid_locked'), //用户唯一识别
            str: scan, //端口号
          }
          api.form_('Scan/scan', data, null, function success(res) {
            console.log(res.data)
            switch (res.data.result_code) {
              case "300": //成功
                let uri = JSON.stringify(res.data.data)
                let data = encodeURIComponent(uri)
                wx.setStorageSync('operator_phone', res.data.data.operator_phone)
                wx.redirectTo({
                  url: '../openCharging/openCharging?support_month_card=' + res.data.support_month_card + '&num_id=' + res.data.num_id + '&data=' + data
                })
                break;
              default: //其他
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none'
                })
            }

          }, function fail(e) {
            wx.showToast({
              title: '网络链接失败,请稍后再试',
              icon: 'none'
            })
          })
        }
        that.setData({
          check_index: -1
        })
      }
    })
  }
})